<?php
/**
 * Created by PhpStorm.
 * 订单业务处理
 * User: caicm
 * Date: 2017/6/21
 * Time: 14:53
 */

namespace WMApi\Service;

use WMApi\Model\WmOrderActionModel;
use WMApi\Model\WmOrderClearingModel;
use WMApi\Model\WmOrderGoodsModel;
use WMApi\Model\WmOrderInfoModel;
use WMApi\Model\WmSellerAccountRecordModel;
use WMApi\Model\WmSellerModel;
use WMApi\Model\WmStoreModel;

class SellerOrderService {

    /**
     * 商家添加订单业务
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param string $expect_time 期望配送时间
     * @param int $goods_number 商品数量
     * @param string $consignee 收货人姓名
     * @param int $mobile 收货人电话
     * @param string $postscript 订单备注
     * @param string $province 省份
     * @param string $city 城市
     * @param string $district 区
     * @param string $address 地址
     * @param string $sign_building 地标
     * @param string $address_name 门牌
     * @param int $goods_amount 商品价格
     * @param int $goods_weight 商品重量
     * @return bool|mixed
     */
    public function add_order($seller_id=0, $store_id=0, $expect_time='', $goods_number=0, $consignee='', $mobile=0, $postscript='', $province='', $city='', $district='', $address='', $sign_building='', $address_name='', $goods_amount=0, $goods_weight=0){
        $store_service = new SellerStoreService();
        $order_model = new WmOrderInfoModel();
        $record_model = new WmSellerAccountRecordModel();
        $seller_model = new WmSellerModel();
        $public_service = new PublicServer();
        $action_model = new WmOrderActionModel();
        $order_model->startTrans();

        //配送期望时间
        $expect_time = $public_service->get_expect_time($expect_time);

        //处理地址
        $address_data = $store_service->dispose_address($province, $city, $district, $address);

        //订单号
        $order_sn = get_order_sn();
        $record_note = "支付订单：{$order_sn}配送服务费";

        /**
         * 写入订单表
         */
        $add_order = $order_model->seller_add_order($seller_id, $store_id, $order_sn, $goods_number, $consignee, $mobile, $postscript, $sign_building, $address_name, $address_data, $expect_time, 0, $goods_amount, $goods_weight);

        /**
         * 写入订单操作记录(创建订单)
         */
        $add_action_1 = $action_model->add_action($seller_id, $store_id, $add_order, '创建订单', '商家', 1, 1);

        //订单推送到物流系统
        $bsc_order = $this->post_order_to_bsc($store_id, $add_order, $order_sn);

        /**
         * 写入订单操作记录(推送订单)
         */
        $add_action_2 = $action_model->add_action($seller_id, $store_id, $add_order, '推送订单', '系统', 1, 1, $bsc_order['trunk_line_status'], $bsc_order['tail_end_status']);

        /**
         * 修改订单配送服务
         */
        $update_shipping = $order_model->update_shipping_service($add_order, $bsc_order['order_freight'],  $bsc_order['trunk_line_status'], $bsc_order['tail_end_status']);

        /**
         * 修改商家账户余额
         */
        $update_account_money = $seller_model->dec_account_money($seller_id, $bsc_order['order_freight']);

        //商家账户余额
        $account_money = $seller_model->get_account_money($seller_id);

        /**
         * 写入账户余额操作记录
         */
        $add_record = $record_model->add_record($seller_id, $store_id, 5, $add_order, 1, $bsc_order['order_freight'], $record_note, $account_money);


        if($add_action_1 !== false && $add_action_2 !== false && $add_order !== false && $update_shipping !== false && $update_account_money !== false && $add_record !== false){
            $order_model->commit();
            return $add_order;
        }else{
            $order_model->rollback();
            return false;
        }

    }

    /**
     * 订单推送到物流系统
     * Created By caicm
     * @param int $store_id 店铺id
     * @param int $order_id 订单id
     * @param string $order_sn 订单编号
     * @return array
     */
    protected function post_order_to_bsc($store_id=0, $order_id=0, $order_sn=''){
        $store_model = new WmStoreModel();
        $bsc_service = new BscService();

        //物流取货点
        $scc_id = $store_model->find_scc_id($store_id);

        //推送订单
        $state = $bsc_service->post_order($order_id, $scc_id);
        if($state['status'] != 1){
            returnApiError($state['error_msg'] ? ($state['status'].":".$state['error_msg']) : ($state['status'].":".'物流系统配置有误'));
        }

        return $this->get_order_to_bsc($order_sn);

    }

    /**
     * 查询物流订单
     * Created By caicm
     * @param string $order_sn
     * @return array
     */
    protected function get_order_to_bsc($order_sn=''){
        $bsc_service = new BscService();
        //查询物流系统订单
        $bsc_order = $bsc_service->select_order_status($order_sn);
        if($bsc_order['status'] != 1){
            returnApiError($bsc_order['error_msg'] ? $bsc_order['error_msg'] : '物流系统配置有误');
        }

        $bsc_data = explode('-', $bsc_order['now_status_code']);

        return array(
            'order_freight' => $bsc_order['order_freight'],
            'trunk_line_status' => $bsc_data[0],
            'tail_end_status' => $bsc_data[1],
        );

    }

    /**
     * 获取订单菜单列表
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @return mixed
     */
    public function get_order_menu_list($seller_id=0, $store_id=0){
        $order_model = new WmOrderInfoModel();
        $data = array(
            array(
                'order_state' => 1,
                'name' => '待接单',
                'goods_number' => $order_model->find_order_state_count($seller_id, $store_id, 0, 1)
            ),
            array(
                'order_state' => 2,
                'name' => '已接单',
                'goods_number' => $order_model->find_order_state_count($seller_id, $store_id, 1, 1)
            ),
            array(
                'order_state' => 3,
                'name' => '骑手已接单',
                'goods_number' => $order_model->find_order_state_count($seller_id, $store_id, 1, 2)
            ),
            array(
                'order_state' => 4,
                'name' => '配送中',
                'goods_number' => $order_model->find_order_state_count($seller_id, $store_id, 1, 3)
            ),
            array(
                'order_state' => 5,
                'name' => '确认收货',
                'goods_number' => $order_model->find_order_state_count($seller_id, $store_id, 1, 4)
            )

        );

        return $data;
    }

    /**
     * 获取订单列表
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param int $order_state 订单状态 1-待接单 2-已接单 3-骑手已接单 4-配送中 5-确认收货
     * @param int $page  分页
     * @return array|float|int
     */
    public function get_order_list($seller_id=0, $store_id=0, $order_state=1, $page=1){
        $order_model = new WmOrderInfoModel();

        //获取订单状态
        $order_state_data = $this->get_order_state($order_state);

        //订单总数
        $order_count = $order_model->find_order_state_count($seller_id, $store_id, $order_state_data['seller_status'], $order_state_data['tail_end_status']);

        $data = show_page($order_count, $page);
        $order_list = $order_model->find_orderlist_by_state($seller_id, $store_id, $order_state_data['seller_status'], $order_state_data['tail_end_status'], $data['firstpage'].','.$data['pagesize']);

        foreach ($order_list as $key=>$value){
            $order_list[$key]['goods_list'] = $this->get_order_goods($value['order_id']);
            $order_list[$key]['add_time'] = get_date($order_list[$key]['add_time']);
            $order_list[$key]['seller_time'] = get_date($order_list[$key]['seller_time']);
            $order_list[$key]['shipping_confirm_time'] = get_date($order_list[$key]['shipping_confirm_time']);
            $order_list[$key]['shipping_time'] = get_date($order_list[$key]['shipping_time']);
            $order_list[$key]['pay_time'] = get_date($order_list[$key]['pay_time']);
            $order_list[$key]['confirm_time'] = get_date($order_list[$key]['confirm_time']);
            $order_list[$key]['shipping_expect_time'] = local_date('Y.m.d [H:i', $order_list[$key]['shipping_expect_time_start']) .'-'. local_date('H:i]', $order_list[$key]['shipping_expect_time_end']);
            $order_list[$key]['order_state'] = $order_state;
            unset($order_list[$key]['shipping_expect_time_start']);
            unset($order_list[$key]['shipping_expect_time_end']);
        }
        $data['order_list'] = $order_list;
        return $data;

    }

    /**
     * 获取订单商品列表
     * Created By caicm
     * @param int $order_id
     * @return mixed
     */
    protected function get_order_goods($order_id=0){
        $order_goods_model = new WmOrderGoodsModel();
        $goods_list = $order_goods_model->find_order_goods_list($order_id);
        foreach ($goods_list as $key=>$val){
            $goods_list[$key]['goods_name'] = get_goods_name($val['goods_name'], $val['main_attr_value_name'], $val['sec_attr_value_name']);
            unset($goods_list[$key]['main_attr_value_name']);
            unset($goods_list[$key]['sec_attr_value_name']);
        }
        return $goods_list;

    }

    /**
     * 修改商家状态
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param int $order_id 订单id
     * @param int $seller_status 商家状态 1-接单 2-拒单 3-取消订单
     * @return bool
     */
    public function order_operation($seller_id=0, $store_id=0, $order_id=0, $seller_status=0){
        $order_model = new WmOrderInfoModel();
        $seller_model = new WmSellerModel();
        $record_model = new WmSellerAccountRecordModel();
        $action_model = new WmOrderActionModel();

        $order_model->startTrans();
        $update_account_money = true;
        $add_order_action_2 = true;
        $add_record = true;

        //订单详情
        $order_info = $order_model->find_order_info($seller_id, $store_id, 0, 0, $order_id);
        if($order_info['tail_end_status'] != 1) returnApiError('订单已在配送状态，不能修改');
        if($order_info['seller_status'] == 3) returnApiError('订单已是取消状态，不能修改');

        //接单、拒单
        if($seller_status == 1 || $seller_status==2){
            if($order_info['order_type'] == 1) returnApiError('商家配送订单，不能修改');
            if($order_info['seller_status'] == 1) returnApiError('订单已是接单状态，不能修改');
            if($order_info['seller_status'] == 2) returnApiError('订单已是拒单状态，不能修改');
        }

        if($seller_status == 1) $remark ='商家接单';
        if($seller_status == 2) $remark ='商家拒单';

        //商家取消配送订单
        if($seller_status == 3){
            if($order_info['order_type'] != 1) {
                returnApiError('不是商家配送订单，不能修改');
            }
            if($order_info['tail_end_status'] != 1){
                returnApiError('该订单配送已接单，不能取消');
            };

            $bsc_service = new BscService();
            $cancel_state = $bsc_service->order_cancel($order_info['order_sn']);
            if($cancel_state['status'] != 1){
                returnApiError($cancel_state['error_msg']?$cancel_state['error_msg']:'物流系统修改失败');
            }

            $record_note = "取消订单：{$order_info['order_sn']}配送服务费";

            /**
             * 修改商家账户余额
             */
            $update_account_money = $seller_model->add_account_money($seller_id, $order_info['shipping_service_fee']);

            /**
             * 商家账户余额
             */
            $account_money = $seller_model->get_account_money($seller_id);

            /**
             * 写入账户余额操作记录
             */
            $add_record = $record_model->add_record($seller_id, $store_id, 6, $order_id, 1, $order_info['shipping_service_fee'], $record_note, $account_money);

            $remark ='商家取消订单';
        }

        $shipping_service_fee = 0;
        $trunk_line_status = 1;
        $tail_end_status =1;


        /**
         * 写入订单操作记录-修改订单
         */
        $add_order_action_1 = $action_model->add_action($seller_id, $store_id, $order_info['order_id'], $remark, '商家', 1, $seller_status, $order_info['trunk_line_status'], $order_info['tail_end_status']);

        //商家接单-处理推送到物流系统
        if($seller_status == 1){
            //订单推送到物流系统
            $bsc_order = $this->post_order_to_bsc($store_id, $order_info['order_id'], $order_info['order_sn']);
            $shipping_service_fee = $bsc_order['order_freight'];
            $trunk_line_status = $bsc_order['trunk_line_status'];
            $tail_end_status = $bsc_order['tail_end_status'];

            /**
             * 写入订单操作记录(推送订单)
             */
            $add_order_action_2 = $action_model->add_action($seller_id, $store_id, $order_info['order_id'], '推送订单', '系统', 1, 1, $trunk_line_status , $tail_end_status);

        }

        /**
         * 修改订单状态
         */
        $order_state = $order_model->update_seller_status($seller_id, $store_id, $order_id, $seller_status, $shipping_service_fee, $trunk_line_status, $tail_end_status);

        if($order_state && $update_account_money && $add_record && $add_order_action_1 && $add_order_action_2){
            $order_model->commit();
            return true;
        }else{
            $order_model->rollback();
            return false;
        }

    }

    /**
     * 获取订单状态
     * Created By caicm
     * @param $order_state
     * @return array
     */
    protected function get_order_state($order_state){
        switch ($order_state){
            //待接单
            case 1:
                $seller_status=0;
                $tail_end_status=1;
                break;

            //已接单
            case 2:
                $seller_status=1;
                $tail_end_status=1;
                break;

            //骑手已接单
            case 3:
                $seller_status=1;
                $tail_end_status=2;
                break;

            //配送中
            case 4:
                $seller_status=1;
                $tail_end_status=3;
                break;

            //确认收货
            case 5:
                $seller_status=1;
                $tail_end_status=4;
                break;
        }

        return array(
            'seller_status' => $seller_status,
            'tail_end_status' => $tail_end_status
        );

    }


    /**
     * 商家订单结算
     * Created By caicm
     */
    public function seller_order_clearing(){
        $order_model = new WmOrderInfoModel();
        $order_info = $order_model->get_clearing_list();

        foreach ($order_info as $key=>$value){
            $state = $this->dispose_clearing($value);
            if($state){
                $data['ok'][$key] = $value['order_id'];
            }else{
                $data['no'][$key] = $value['order_id'];
            }
        }
        return $data;
    }

    /**
     * 处理结算
     * Created By caicm
     * @param $order_info
     * @return bool
     */
    protected function dispose_clearing($order_info){
        $order_id = $order_info['order_id'];                            //订单id
        $order_sn = $order_info['order_sn'];                            //订单号
        $seller_id = $order_info['seller_id'];                          //商家id
        $store_id = $order_info['store_id'];                            //店铺id
        $uid = $order_info['uid'];                                      //用户id
        $shipping_service_fee = $order_info['shipping_service_fee'];    //订单配送服务费
        $pay_fee = $order_info['pay_fee'];                              //订单支付总额
        $income_money = $pay_fee - $shipping_service_fee;               //收入金额
        $record_note = "订单结算，订单号：{$order_sn}";

        $seller_model = new WmSellerModel();
        $clearing_model = new WmOrderClearingModel();
        $record_model = new WmSellerAccountRecordModel();
        $order_model = new WmOrderInfoModel();
        $seller_model->startTrans();

        /**
         * 修改商家账户余额
         */
        $update_account_money = $seller_model->add_account_money($seller_id, $income_money);

        //商家账户余额
        $account_money = $seller_model->get_account_money($seller_id);

        /**
         * 写入操作记录
         */
        $add_record = $record_model->add_record($seller_id, $store_id, 3, $order_id, 2, $income_money, $record_note, $account_money);

        /**
         * 写入结算记录
         */
        $add_clearing = $clearing_model->add_order_clearing($seller_id, $store_id, $order_id, $order_sn, $uid, $income_money, $pay_fee, $shipping_service_fee, $account_money);

        /**
         * 修改订单结算状态
         */
        $update_order = $order_model->update_order_clearing_state($order_id);

        if($update_account_money && $add_record && $add_clearing && $update_order){
            $seller_model->commit();
            return true;
        }else{
            $seller_model->rollback();
            return false;
        }

    }


}